<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="姓名"    prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable size="small">
          <el-option
            v-for="dict in genderStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学籍"  prop="occupation" >
        <el-input
          v-model="queryParams.occupation"
          placeholder="请输入学籍"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="时间段" prop="dates">
          <el-date-picker
            v-model="dates"
            type="datetimerange"
            :clearable="false"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      <span >
        <svg-icon icon-class="peoples" />用户量
        <span class="pull-right">{{ client.visitorNum }}</span>
      </span>
      </el-col>
      <el-col :span="1.5">
      <span >
        <svg-icon icon-class="eye-open" />访问次数
        <span class="pull-right">{{ client.viewNum }}</span>
      </span>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx:user:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />、
      <el-table-column label="头像" align="center" prop="headUrl" >
        <template slot-scope="scope">
          <el-image :src="scope.row.headUrl" style="height: 40px;width: 40px"/>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="性别" align="center" :formatter="genderFormat"/>

      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="学籍" align="center" prop="occupation"/>
      <el-table-column label="学校" align="center" prop="education"/>
      <el-table-column label="注册时间" align="center" prop="createTime"/>
      <el-table-column label="状态" align="center" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="客户端" align="center" v-if="handleCheckRole('admin')" :show-overflow-tooltip="true" :formatter="clientFormat"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微信用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="昵称" align="center" prop="nickName" />
        <el-table-column label="头像" align="center" prop="headUrl" >
          <template slot-scope="scope">
            <el-image :src="scope.row.headUrl" />
          </template>
        </el-table-column>
        <el-table-column label="唯一标识" align="center" prop="openid" width="320"/>
        <el-table-column label="手机号" align="center" prop="phone" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listGxUser, getGxUser, delUser, addUser, updateUser, exportUser} from "@/api/wx/user";
import { checkPermi,checkRole } from "@/utils/permission";
import { listClient,getStatics } from "@/api/wx/client";

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 性别字典
      genderStatus:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        headUrl: undefined,
        openid: undefined,
        phone: undefined,
        status: undefined,
        clientId: undefined,
        realName:undefined,
        education:undefined,
        occupation:undefined,
        updateTime:undefined,
        createTime:undefined,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      userId: undefined,
      dates:[],
      userList:[],
      client:{}
    };
  },
  created() {
    // 性别字典翻译
    this.getDicts("wx_user_sex").then(response => {
      this.genderStatus = response.data;
    });
    // 用户状态字典翻译
    this.getDicts("wx_user_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getList();

    listClient().then(response => {
      this.clientList = response.rows;
    });
  },
  methods: {
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.realName + '"用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return updateUser({id:row.id, status:row.status});
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 查询微信用户列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams)
      listGxUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getStatics({id:11,createTime:this.queryParams.createTime,updateTime:this.queryParams.updateTime}).then(res=>{
        this.client = res.data;
      })
    },
    handleCheckPermi(v){
      return checkPermi([v]);
    },
    handleCheckRole(v){
      return checkRole([v]);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 性别字典翻译
    genderFormat(row) {
      return this.selectDictLabel(this.genderStatus, row.gender);
    },
    // 状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    clientFormat(row){
      let txt = '';
      this.clientList.filter(e=>{
        if (e.id == row.clientId){
          txt = e.name;
          return;
        }
      })
      return txt;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        nickName: undefined,
        realName:undefined,
        education:undefined,
        occupation:undefined,
        headUrl: undefined,
        openid: undefined,
        phone: undefined,
        delFlag: undefined,
        createTime: undefined,
        updateTime: undefined,
        status: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.dates.length>0){
        this.queryParams.createTime = this.dates[0];
        this.queryParams.updateTime = this.dates[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dates = [];
      this.queryParams.createTime = undefined;
      this.queryParams.updateTime = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信用户";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGxUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改微信用户";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除微信用户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有微信用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
